package com.example.sneakerappforme1105;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.sneakerappforme1105.adapter.RecyclerHomeAdapter;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.dao.GoodsDao;
import com.example.sneakerappforme1105.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchGoodsActivity extends AppCompatActivity {
    private String TAG = "SearchGoodActivity";
    private ImageView back;
    private RecyclerView rv_display_search;
    private GoodsDao goodsDao;
    private String searchString;    // 接收搜索过来的字符串
    private List<Goods> goodsList;
    private List<Goods> remainList;
    private SwipeRefreshLayout srl_refresh;
    private RecyclerHomeAdapter adapter;
    private SearchView mSearch;
    private LinearLayout ll_empty2;
    private LinearLayout ll_content2;
    private Long mUserId;
    private Long mCartId;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_goods);

        goodsDao = MainApplication.getInstance().getAppDatabase().goodsDao();
        searchString = getIntent().getStringExtra("SearchString");
        Log.d(TAG,"接收来要搜索的字符串为: "+searchString);
        srl_refresh = findViewById(R.id.srl_refresh_search);
        rv_display_search = findViewById(R.id.rv_display_search);
        back = findViewById(R.id.search_back);

        ll_content2 = findViewById(R.id.ll_content2);
        ll_empty2 = findViewById(R.id.ll_empty2);

        // 传回去
        mUserId = getIntent().getLongExtra("userId",0L);
        mCartId = getIntent().getLongExtra("cartId",0L);

        goodsList = goodsDao.queryAllGoods();   // 查询所有的商品
        Log.d(TAG,"查询到商品数据有："+goodsList.size());
        remainList = new ArrayList<>();
        List<Long> ids = new ArrayList<>(); // 存储pos
        Map<Integer,Long> map = new HashMap<>();
        int id = 0;
        for(Goods good: goodsList){
            if(good.getName().toLowerCase().contains(searchString.toLowerCase())){
                remainList.add(good);
                map.put(id,good.getGoodsId());
                id++;
            }
        }
        adapter = new RecyclerHomeAdapter(this,remainList);
        adapter.setOnItemClickListener(new RecyclerHomeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {  // 重写监听方法
                // 点击 进入详情页  卖鞋的详情页
//                Goods select = goodsList.get(position); // 点击的商品 id->position的映射
                Log.d(TAG,"你点击的是"+position);
                Intent intent = new Intent(SearchGoodsActivity.this, GoodsDetailActivity.class);    // 跳转到详情页
                intent.putExtra("goodsId", map.get(position));
                intent.putExtra("userId",mUserId);
                intent.putExtra("cartId",mCartId);
                Log.d(TAG,"你点击的是 "+map.get(position));
                startActivity(intent);
            }
        });

        GridLayoutManager manager = new GridLayoutManager(SearchGoodsActivity.this, 2);
        rv_display_search.setLayoutManager(manager);
        rv_display_search.setAdapter(adapter);

        mSearch = findViewById(R.id.search);
        mSearch.setOnSearchClickListener(v -> {
            Intent intent = new Intent(SearchGoodsActivity.this, SearchActivity.class);
            intent.putExtra("userId",mUserId);
            intent.putExtra("cartId",mCartId);
            startActivity(intent);
            // 清除焦点，确保可以再次点击
            mSearch.clearFocus();
        });

        // 获取 SearchView 内部的 EditText
        EditText searchEditText = mSearch.findViewById(androidx.appcompat.R.id.search_src_text);

        // 设置只读
        searchEditText.setFocusable(false);
        searchEditText.setFocusableInTouchMode(false);
        searchEditText.setCursorVisible(false);
        searchEditText.setKeyListener(null);

        // 进入数据库进行查询
        showCount();

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }


    private Handler mHandler = new Handler(Looper.myLooper());



    // 刷新任务
//    private Runnable mRefresh = new Runnable() {
//        @Override
//        public void run() {
//            srl_refresh.setRefreshing(false);   // 结束下拉刷新布局的刷新动作
//            // 更新服装信息列表
//            for(int i = goodsList.size()-1, count=0; count<5; count++){
//                Goods item = goodsList.get(i);
//                goodsList.remove(i);
//                goodsList.add(0, item);
//            }
//            adapter.notifyDataSetChanged(); // 通知适配器列表数据发生变化
//            rv_display_search.scrollToPosition(0); // 让循环试图滚动到第一项所在位置
//        }
//    };

//    @Override
//    public void onRefresh() {
//        mHandler.postDelayed(mRefresh,2000);
//    }
    // 根据输入框的文字，查找带相关文字的商品并展示

    private void showCount(){
        if(remainList.size()==0){
            // 购物车项 的 数量为0
            ll_content2.setVisibility(View.GONE);

            ll_empty2.setVisibility(View.VISIBLE);
        }else{
            ll_content2.setVisibility(View.VISIBLE);

            ll_empty2.setVisibility(View.GONE);
        }
    }
}